/**
 * @(#)ClientConnection.java, 2012-2-22. Copyright 2012 Yodao, Inc. All rights
 *                            reserved. YODAO PROPRIETARY/CONFIDENTIAL. Use is
 *                            subject to license terms.
 */
package com.buaaer.rpc;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * @author wangheng
 */
public class ClientConnection {
    
    IoSession ioSession;
    

    public ClientConnection() {
        
        IoConnector ioConnector = new NioSocketConnector();

        ioConnector.getFilterChain().addLast("codec", 
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        
        ClientConnectionHandler clientConnectionHandler = new ClientConnectionHandler();
        ioConnector.setHandler(clientConnectionHandler);

        ConnectFuture connectFuture = ioConnector
                .connect(new InetSocketAddress("localhost", 12345));
        connectFuture.awaitUninterruptibly();
        ioSession = connectFuture.getSession();
        
    }
    
    public void sentMessage(Object message) {
        ioSession.write(message);
        System.out.println("message send" + message);
    }

}
